package luren.king.wechatlite.activity;

import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.json.JSONObject;

import luren.king.wechatlite.R;
import luren.king.wechatlite.config.Config;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {
    private EditText emailEditText;
    private EditText passwordEditText;
    private EditText check_code;

    private Boolean is_email_correct = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_register);

        // 使用类级别的变量，而不是创建新的局部变量
        emailEditText = (EditText) findViewById(R.id.register_et_email);
        passwordEditText = (EditText) findViewById(R.id.register_et_password);
        check_code = (EditText) findViewById(R.id.register_et_checkcode);

        // 找到按钮（这里需要显式地指定为Button类型）
        View registerBack = findViewById(R.id.register_back);
        //返回登录
        View registerCode = findViewById(R.id.register_getcode);
        //获取验证码
        View registerButton = findViewById(R.id.register_button);
        //注册
        // 设置点击事件监听器
        registerBack.setOnClickListener(v -> {
            // 当点击按钮时，结束当前Activity
            finish();
        });


        // OkHttpClient实例
        OkHttpClient client = new OkHttpClient();

        registerButton.setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            // 加载自定义的布局
            LayoutInflater inflater = getLayoutInflater();
            View dialogView = inflater.inflate(R.layout.custom_loading_dialog, null);

            // 设置自定义背景
            dialogView.setBackgroundResource(R.drawable.dialog_background);

            // 设置Dialog的视图
            builder.setView(dialogView);

            // 创建并显示AlertDialog
            AlertDialog alertDialog = builder.create();
            alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置窗口背景透明
            alertDialog.setCancelable(false); // 禁用取消操作（例如点击外部取消）

            alertDialog.show();
            new Thread(){
                @Override
                public void run() {
                    Looper.prepare();
                    try {
                        String email = emailEditText.getText().toString();
                        String password = passwordEditText.getText().toString();
                        String code = check_code.getText().toString();
                        if (email.isEmpty() || password.isEmpty() || code.isEmpty()){
                            alertDialog.dismiss();
                            Toast.makeText(RegisterActivity.this, "请补全信息", Toast.LENGTH_LONG).show();
                            return;
                        }
                        JSONObject user = new JSONObject();
                        user.put("email", email);
                        user.put("password", password);
                        user.put("checkCodeKey", code);
                        MediaType mediaType = MediaType.parse("application/json");
                        RequestBody body = RequestBody.create(user.toString(), mediaType);
                        Request request = new Request.Builder()
                                .url(Config.DEFAULT_URL + "/web/register")
                                .method("POST", body)
                                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                                .addHeader("Content-Type", "application/json")
                                .build();
                        Response response = client.newCall(request).execute();
                        JSONObject json = new JSONObject(response.body().string());
                        runOnUiThread(() -> {
                            try {
                                alertDialog.dismiss();
                                Toast.makeText(RegisterActivity.this, json.getString("msg"), Toast.LENGTH_LONG).show();
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        });
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    Looper.loop();
                }
            }.start();
        });



        // 为registerCode按钮设置点击事件监听器
        registerCode.setOnClickListener(v -> {
            String email = emailEditText.getText().toString();
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            // 加载自定义的布局
            LayoutInflater inflater = getLayoutInflater();
            View dialogView = inflater.inflate(R.layout.custom_loading_dialog, null);

            // 设置自定义背景
            dialogView.setBackgroundResource(R.drawable.dialog_background);

            // 设置Dialog的视图
            builder.setView(dialogView);

            // 创建并显示AlertDialog
            AlertDialog alertDialog = builder.create();
            alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置窗口背景透明
            alertDialog.setCancelable(false); // 禁用取消操作（例如点击外部取消）

            alertDialog.show();
            if (email.isEmpty()){
                alertDialog.dismiss();
                Toast.makeText(RegisterActivity.this, "请补全信息", Toast.LENGTH_LONG).show();
                return;
            }
            new Thread(){
                @Override
                public void run() {
                    Looper.prepare();
                    try {
                        Request request = new Request.Builder()
                                .url(Config.DEFAULT_URL + "/web/GetCheckCodeKey/"+email)
                                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                                .build();
                        Response response = client.newCall(request).execute();
                        alertDialog.dismiss();
                        Toast.makeText(RegisterActivity.this, new JSONObject(response.body().string()).getString("msg"), Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    Looper.loop();
                }
            }.start();
        });
    }
}